package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"live/models"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type AnchorController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 主播添加

func (c *AnchorController) Add() {
	name := c.GetString("name")
	sex := c.GetString("sex")
	cate := c.GetString("cate")
	intro := c.GetString("intro")
	img := c.GetString("img")
	fans, _ := c.GetInt("fans")
	anchor := models.Anchor{
		Name:  name,
		Sex:   sex,
		Cate:  cate,
		Intro: intro,
		Img:   img,
		Fans:  fans,
	}
	tx := models.DB.Begin() //开启事务
	// 入库之前做数据验证
	err := tx.Create(&anchor).Error
	if err != nil {
		tx.Rollback() //事务会滚
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		tx.Commit() //事务提交
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 主播列表

func (c *AnchorController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1) //接收当前页
	size, _ := c.GetInt("size", 5) //接收每页条数
	name := c.GetString("name")    //三
	cate := c.GetString("cate")
	query := models.DB.Model(&models.Anchor{})

	// 多条件搜索的思路： 有条件拼接条件
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	if cate != "" {
		query = query.Where("cate = ?", cate)
	}
	key := "list-" + strconv.Itoa(page) + "-" + name + "-" + cate
	val, err := models.Rdb.Get(key).Result()
	//判断缓存中是否有数据，有直接返回，没有在查询数据库，并且存入数据库
	pageData := make(map[string]interface{}) //容器
	if err != nil {
		//查数据库
		var count int64 //总条数
		err = query.Count(&count).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "总数查询失败",
			}
			c.ServeJSON()
			return
		}
		var anchor []models.Anchor                                 //切片
		offset := (page - 1) * size                                //偏移量
		err = query.Limit(size).Offset(offset).Find(&anchor).Error //核心
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "查询失败",
			}
			c.ServeJSON()
			return
		}

		pageData["count"] = count   //总条数
		pageData["anchor"] = anchor //主播数据

		jsonByte, _ := json.Marshal(&pageData)
		value := string(jsonByte)
		models.Rdb.Set(key, value, time.Second*20)

		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-mysql",
			Data: pageData,
		}
		c.ServeJSON()
	} else {
		//返回缓存
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

// 主播删除

func (c *AnchorController) Delete() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Anchor{}, id).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		key := "anchor-" + strconv.Itoa(id)
		models.Rdb.Del(key)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 主播详情

func (c *AnchorController) Info() {
	id, _ := c.GetInt("id")
	RankKey := "Rank"
	models.Rdb.ZIncrBy(RankKey, 1, strconv.Itoa(id))
	// 记录排行榜数据
	key := "anchor-" + strconv.Itoa(id)
	//判断缓存中是否有数据，有的话直接读取缓存,没有的话查询数据库，并且存入缓存（原理）
	val, err := models.Rdb.Get(key).Result() //获取缓存
	var anchor models.Anchor
	if err != nil {
		// 查询数据库
		err = models.DB.Where("id = ?", id).First(&anchor).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		// 存入缓存
		jsonByte, _ := json.Marshal(anchor)
		value := string(jsonByte)
		models.Rdb.Set(key, value, 0)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "详情查询成功-mysql",
			Data: anchor,
		}
		c.ServeJSON()

	} else {
		json.Unmarshal([]byte(val), &anchor)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "详情查询成功-redis",
			Data: anchor,
		}
		c.ServeJSON()
	}
}

// 主播修改

func (c *AnchorController) Update() {
	name := c.GetString("name")
	sex := c.GetString("sex")
	cate := c.GetString("cate")
	intro := c.GetString("intro")
	img := c.GetString("img")
	fans, _ := c.GetInt("fans")
	id, _ := c.GetInt("id")

	anchor := models.Anchor{
		Name:  name,
		Sex:   sex,
		Cate:  cate,
		Intro: intro,
		Img:   img,
		Fans:  fans,
	}
	err := models.DB.Where("ID =?", id).Updates(&anchor).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}

}

//文件上传

func (c *AnchorController) Upload() {
	file, header, err := c.GetFile("img") //接收文件
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "请选择文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close() //关闭文件
	// 文件大小验证
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件过大，不得超过2M",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	//格式验证
	ext := strings.ToLower(filepath.Ext(header.Filename)) //后缀
	allowExt := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	if !allowExt[ext] {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件格式错误，必须是png,jpg,jpeg格式",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename //指定上传路径
	err = c.SaveToFile("img", path)         //上传
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgUrl := "http://127.0.0.1:8088/" + path // 返回给前端的图片路径
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "上传成功",
			Data: imgUrl,
		}
		c.ServeJSON()
	}
}

// 排行榜

func (c *AnchorController) Rank() {
	key := "Rank"
	rank, err := models.Rdb.ZRevRange(key, 0, 10-1).Result()
	//[12 3 7]
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "排行榜获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	var anchors []models.Anchor
	for _, i := range rank {
		var anchor models.Anchor
		err = models.DB.Model(models.Anchor{}).Where("ID = ?", i).First(&anchor).Error
		if err != nil {
			break
		}
		anchors = append(anchors, anchor)
	}
	c.Data["json"] = JsonRes{
		Code: 200,
		Msg:  "展示成功",
		Data: anchors,
	}
	c.ServeJSON()
}
